﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TheHeGeo.Util;
using TheHeGeoDao;

namespace TheHeGeo.UserControl
{
    public partial class UcSensorVisualizer : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadGrlDuAn();
                Session[SessionConst.SES_GRL_PICTURE_SENSOR] = null;
                if (!string.IsNullOrEmpty(Request.QueryString["d"]))
                {
                    int temp = Convert.ToInt32(Request.QueryString["d"]);
                    grlDuAn.ValueChanged -= grlDuAn_ValueChanged;
                    grlDuAn.Value = temp;
                    grlDuAn.ValueChanged += grlDuAn_ValueChanged;
                    LoadGrlData(temp);

                    if (!string.IsNullOrEmpty(Request.QueryString["p"]))
                    {
                        int imgId = Convert.ToInt32(Request.QueryString["p"]);
                        grlData.ValueChanged -= grlData_ValueChanged;
                        if (imgId < 0 && grlData.GridView.VisibleRowCount > 0)
                            imgId = Convert.ToInt32(grlData.GridView.GetRowValues(0, "Id"));
                        grlData.Value = imgId;
                        grlData.ValueChanged += grlData_ValueChanged;
                        bool canEdit = CheckCanEdit();
                        if (!string.IsNullOrEmpty(Request.QueryString["e"]))
                        {
                            grlSensor.Visible = FileUpload1.Visible = btAdd.Visible =
                            btCancel.Visible=btDelete.Visible = btUpdate.Visible = canEdit;
                            LoadGrlSensor(imgId, temp);
                            LoadImage(imgId, true);
                        }
                        else
                        {
                            LoadImage(imgId, false);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Request.QueryString["e"]))
                        {
                            bool canEdit = CheckCanEdit();
                            FileUpload1.Visible = btAdd.Visible = canEdit;
                            LoadGrlSensor(-1, temp);
                        }
                    }
                }
            }
            else
            {
                grlData.DataSource = Session[SessionConst.SES_GRL_PICTURE_SENSOR];
                grlDuAn.DataSource = Session[SessionConst.SES_GRL_PICUTRE_DU_AN];
                grlSensor.DataSource = Session[SessionConst.SES_GRL_PICTURE_EDIT_SENSOR];
            }
        }

        protected bool CheckCanEdit()
        {
            string nsd = ((SessionUser) Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            int mda = Convert.ToInt32(grlDuAn.Value);
            PhanQuyenDuAn obj =
                DaoHelper.Entities.PhanQuyenDuAns.FirstOrDefault(p => p.UserName == nsd && p.MaDuAn == mda);
            if (obj != null)
            {
                return obj.Role == "777";
            }
            return false;
        }

        protected void LoadGrlDuAn()
        {
            string nsd = ((SessionUser) Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            List<DuAn> data = (from p in DaoHelper.Entities.PhanQuyenDuAns
                join d in DaoHelper.Entities.DuAns on p.MaDuAn equals d.MaDuAn
                where p.UserName == nsd
                select d
                ).ToList();
            Session[SessionConst.SES_GRL_PICUTRE_DU_AN] = data;
            grlDuAn.DataSource = data;
            grlDuAn.DataBind();
        }

        protected void LoadGrlSensor(int imgId, int maDa)
        {
            var dataCheck = (from s in DaoHelper.Entities.SensorInPhotoes
                join i in DaoHelper.Entities.Sensors on s.MaSensor equals i.MaSensor
                where (s.IdImage == imgId)
                select new
                {
                    i.MaSensor
                }
                ).ToList();
            var data = (from s in DaoHelper.Entities.Sensors
                join i in DaoHelper.Entities.ThietBis on s.MaThietBi equals i.MaThietBi
                join d in DaoHelper.Entities.DuAns on i.MaDuAn equals d.MaDuAn
                where (d.MaDuAn == maDa &&i.Status==0)
                select new {s.MaSensor, s.TenSensor, s.MoTa}).ToList();
            Session[SessionConst.SES_GRL_PICTURE_EDIT_SENSOR] = data;
            grlSensor.DataSource = data;
            grlSensor.DataBind();

            grlSensor.ValueChanged -= grlSensor_ValueChanged;
            foreach (var d in dataCheck)
            {
                grlSensor.GridView.Selection.SelectRowByKey(d.MaSensor);
            }
            grlSensor.ValueChanged += grlSensor_ValueChanged;
        }

        protected void LoadGrlData(int maDa)
        {
            string nsd = ((SessionUser) Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var data = (from p in DaoHelper.Entities.PhanQuyenDuAns
                join i in DaoHelper.Entities.ImageDuAns on p.MaDuAn equals i.MaDuAn
                where (p.UserName == nsd && p.MaDuAn == maDa)
                select new
                {
                    p.Role,
                    i.ChuThich,
                    i.Id
                }
                ).ToList();
            Session[SessionConst.SES_GRL_PICTURE_SENSOR] = data;
            grlData.DataSource = data;
            grlData.DataBind();
        }

        protected void grlDuAn_ValueChanged(object sender, EventArgs e)
        {
            Response.Redirect("~/User/SensorVisualizer.aspx?d=" + grlDuAn.Value);
        }

        protected void grlData_ValueChanged(object sender, EventArgs e)
        {
            Response.Redirect("~/User/SensorVisualizer.aspx?d=" + grlDuAn.Value + "&p=" + grlData.Value);
        }

        protected void LoadImage(int imgId, bool canMove)
        {
            DaoHelper.ReOpen();
            DateTime defaultDate = DateTime.Now;
            int maDa = Convert.ToInt32(grlDuAn.Value);
            var ds = new List<string>();
            if (canMove)
            {
                List<object> temp = grlSensor.GridView.GetSelectedFieldValues("MaSensor");
                ds.AddRange(temp.Select(o => o.ToString()));

            }
            
            var listSersor = !canMove
                ? (from i in DaoHelper.Entities.SensorInPhotoes
                    join s in DaoHelper.Entities.Sensors on i.MaSensor equals s.MaSensor
                    join l in DaoHelper.Entities.SensorLatestValues on s.MaSensor equals l.MaSensor
                        into gj
                    from e in gj.DefaultIfEmpty()
                    where i.IdImage == imgId
                    select new
                    {
                        i.X,
                        i.Y,
                        s.TenSensor,
                        ThoiGianDo = e == null ? defaultDate : e.ThoiGianDo,
                        GiaTri = e == null ? -999.9 : e.GiaTri,
                        s.MaSensor,
                        i.IdImage,
                        i.MaDuAn
                    }
                    ).ToList()
                : (
                    (
                        from t in (from d in ds
                            join s in DaoHelper.Entities.Sensors.AsEnumerable() on d equals s.MaSensor
                            join b in DaoHelper.Entities.ThietBis.AsEnumerable() on s.MaThietBi equals b.MaThietBi
                            join a in DaoHelper.Entities.DuAns.AsEnumerable() on b.MaDuAn equals a.MaDuAn
                            where (a.MaDuAn == maDa && b.Status==0)
                            select s
                            )
                        join i in (DaoHelper.Entities.SensorInPhotoes.AsEnumerable().Where(p=>p.IdImage==imgId)) on t.MaSensor equals i.MaSensor
                            into gj
                        from e in gj.DefaultIfEmpty()
                        select new
                        {
                            X = e != null ? e.X : 40,
                            Y = e != null ? e.Y : 40,
                            t.TenSensor,
                            ThoiGianDo = defaultDate,
                            GiaTri = -999.9,
                            t.MaSensor,
                            IdImage = e != null ? e.IdImage : -1,
                            MaDuAn=maDa,
                        }
                        ).ToList()
                    );
            int index = 0;
            string value = "";

            ImageDuAn firstOrDefault = DaoHelper.Entities.ImageDuAns.FirstOrDefault(p => p.Id == imgId);
            if (firstOrDefault != null)
                ASPxImage1.ImageUrl = firstOrDefault.ImageUrl;
            foreach (var s in listSersor)
            {
                string gt = s.GiaTri.CompareTo(-999.9) != 0
                    ? " Giá trị:" + s.GiaTri + "@ Thời gian đo:" + s.ThoiGianDo.ToString("yyyy/MM/dd HH:mm:ss.ff")
                    : "Không có dữ liệu";
                value += s.MaSensor + "~" + s.X + "~" + s.Y + "~" + s.TenSensor + "~" + gt+"~"+s.MaDuAn + "|";
                index++;
            }
            if (!canMove)
                HfUnMoveable.Value = value.Trim('|');
            else
            {
                HfMoveable.Value = value.Trim('|');
            }
        }

        protected void btEdit_Click1(object sender, EventArgs e)
        {
            if (CheckCanEdit())
            {
                Response.Redirect("~/User/SensorVisualizer.aspx?d=" + grlDuAn.Value + "&p=" + grlData.Value + "&e=1");
            }
        }

        protected void btDelete_Click(object sender, EventArgs e)
        {
            int imgId = Convert.ToInt32(grlData.Value);
            ImageDuAn ig = DaoHelper.Entities.ImageDuAns.FirstOrDefault(p => p.Id == imgId);
            if (ig != null)
            {
                DaoHelper.Entities.ImageDuAns.Remove(ig);
                string file = Server.MapPath(ig.ImageUrl);
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
            }

            IQueryable<SensorInPhoto> ph = DaoHelper.Entities.SensorInPhotoes.Where(p => p.IdImage == imgId);

            DaoHelper.Entities.SensorInPhotoes.RemoveRange(ph);
            DaoHelper.Entities.SaveChanges();
            Response.Redirect("~/User/SensorVisualizer.aspx?d=" + grlDuAn.Value);
        }

        protected void btAdd_Click(object sender, EventArgs e)
        {
            txtChuThich.Text = string.Empty;
            ASPxPopupControl1.ShowOnPageLoad = true;
        }

        protected void grlSensor_ValueChanged(object sender, EventArgs e)
        {
            LoadImage(Convert.ToInt32(grlData.Value), true);
        }

        protected void btpopOk_Click(object sender, EventArgs e)
        {
            lblUpload.Text = string.Empty;
            bool isValid = false;
            int id = -1;
            if (FileUpload1.HasFile)
            {
                string[] validFileTypes = {"bmp", "gif", "png", "jpg", "jpeg"};
                string ext = Path.GetExtension(FileUpload1.PostedFile.FileName).Trim('.');
                if (validFileTypes.Contains(ext))
                {
                    if (FileUpload1.PostedFile.ContentLength <= 1048576)
                    {
                        string folder = "~/UserImages/" +
                                        ((SessionUser) Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
                        string abc = Server.MapPath(folder);
                        if (!Directory.Exists(abc))
                        {
                            Directory.CreateDirectory(abc);
                        }

                        FileUpload1.SaveAs(abc + "\\" + FileUpload1.FileName);
                        string file = folder + "/" + FileUpload1.FileName;
                        var pt = new ImageDuAn
                        {
                            Avatar = false,
                            ImageUrl = file,
                            MaDuAn = Convert.ToInt32(grlDuAn.Value),
                            ChuThich = txtChuThich.Text
                        };
                        DaoHelper.Entities.ImageDuAns.Add(pt);
                        DaoHelper.Entities.SaveChanges();
                        int maDa = Convert.ToInt32(grlDuAn.Value);
                        var data = (from s in DaoHelper.Entities.Sensors
                            join i in DaoHelper.Entities.ThietBis on s.MaThietBi equals i.MaThietBi
                            join d in DaoHelper.Entities.DuAns on i.MaDuAn equals d.MaDuAn
                            where d.MaDuAn == maDa
                            select new {s.MaSensor, s.TenSensor, s.MoTa}).ToList();

                        foreach (var d in data)
                        {
                            var s = new SensorInPhoto
                            {
                                MaDuAn = maDa,
                                MaSensor = d.MaSensor,
                                IdImage = pt.Id,
                                X = 40,
                                Y = 40,
                            };
                            DaoHelper.Entities.SensorInPhotoes.Add(s);
                        }
                        id = pt.Id;
                        DaoHelper.Entities.SaveChanges();
                        isValid = true;
                    }
                    else
                    {
                        lblUpload.Text = "File phải có kích thước nhỏ hơn 1Mb.";
                    }
                }
                else
                {
                    lblUpload.Text = "Vui lòng chọn file ảnh.";
                }
            }
            else
            {
                lblUpload.Text = "Bạn chưa chọn file";
            }
            if (isValid)
            {
                lblUpload.Visible = false;
                Response.Redirect("~/User/SensorVisualizer.aspx?d=" + grlDuAn.Value+"&e=1&p="+id);
            }
            else
            {
                lblUpload.Visible = true;
            }
        }

        protected void btUpdate_Click(object sender, EventArgs e)
        {
            string[] str = HfMoveable.Value.Trim('|').Split('|');
            var ds = new List<string>();
            List<object> temp = grlSensor.GridView.GetSelectedFieldValues("MaSensor");
            ds.AddRange(temp.Select(o => o.ToString()));

            int maDa = Convert.ToInt32(grlDuAn.Value);
            int imgId = Convert.ToInt32(grlData.Value);
            IQueryable<SensorInPhoto> listDelete =
                DaoHelper.Entities.SensorInPhotoes.Where(p => p.MaDuAn == maDa && p.IdImage == imgId);
            DaoHelper.Entities.SensorInPhotoes.RemoveRange(listDelete);
            DaoHelper.Entities.SaveChanges();

            List<SensorInPhoto> listSs= (from s in ds
                let data = str.FirstOrDefault(p => p.StartsWith(s))
                where data != null
                let cs = data.Split('~')
                select new SensorInPhoto()
                {
                    IdImage = imgId, MaDuAn = maDa, MaSensor = s, X = Convert.ToDouble(cs[1]), Y = Convert.ToDouble(cs[2]),
                }).ToList();
            
            DaoHelper.Entities.SensorInPhotoes.AddRange(listSs);
            DaoHelper.Entities.SaveChanges();
            Response.Redirect("~/User/SensorVisualizer.aspx?d=" + grlDuAn.Value + "&p=" + grlData.Value);
        }

        protected void btCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/User/SensorVisualizer.aspx?d=" + grlDuAn.Value + "&p=" + grlData.Value);
        }
    }
}